<?php
namespace YDCMS\core;

class App
{
    /**
     * @var array 应用配置
     */
    protected $config = [];

    /**
     * @var Router 路由实例
     */
    protected $router;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->router = new Router();
        $this->registerRoutes();
    }

    /**
     * 初始化应用
     */
    protected function initialize()
    {
        // 加载配置
        $this->loadConfig();
        
        // 注册错误处理
        $this->registerErrorHandler();
    }

    /**
     * 加载配置
     */
    protected function loadConfig()
    {
        // 加载基础配置
        $configPath = APP_PATH . 'config/';
        $configFiles = glob($configPath . '*.php');
        
        foreach ($configFiles as $file) {
            $key = basename($file, '.php');
            $this->config[$key] = require $file;
        }
    }

    /**
     * 注册错误处理
     */
    protected function registerErrorHandler()
    {
        set_error_handler(function ($errno, $errstr, $errfile, $errline) {
            if (!(error_reporting() & $errno)) {
                return false;
            }
            
            throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
        });
        
        set_exception_handler(function ($e) {
            $this->handleException($e);
        });
    }

    /**
     * 处理异常
     */
    protected function handleException($e)
    {
        // 记录错误日志
        error_log($e->getMessage() . "\n" . $e->getTraceAsString());
        
        // 显示错误信息
        if ($_ENV['APP_DEBUG'] ?? false) {
            echo '<h1>Error</h1>';
            echo '<p>' . $e->getMessage() . '</p>';
            echo '<pre>' . $e->getTraceAsString() . '</pre>';
        } else {
            echo '<h1>500 Internal Server Error</h1>';
        }
    }

    private function registerRoutes()
    {
        // Public routes
        $this->router->get('/', [\YDCMS\controllers\HomeController::class, 'index']);
        
        // Auth routes
        $this->router->get('/auth/login', [\YDCMS\controllers\AuthController::class, 'login']);
        $this->router->post('/auth/login', [\YDCMS\controllers\AuthController::class, 'login']);
        $this->router->get('/auth/register', [\YDCMS\controllers\AuthController::class, 'register']);
        $this->router->post('/auth/register', [\YDCMS\controllers\AuthController::class, 'register']);
        $this->router->get('/auth/logout', [\YDCMS\controllers\AuthController::class, 'logout']);
        
        // Admin login/logout routes
        $this->router->get('/admin/login', [\YDCMS\controllers\AdminController::class, 'login']);
        $this->router->post('/admin/login', [\YDCMS\controllers\AdminController::class, 'login']);
        $this->router->get('/admin/logout', [\YDCMS\controllers\AdminController::class, 'logout']);
        
        // Protected routes
        $this->router->get('/admin/dashboard', [\YDCMS\controllers\AdminController::class, 'dashboard'], [\YDCMS\core\AuthMiddleware::class]);
        $this->router->get('/admin/articles', function() { echo view('admin/articles'); });
        $this->router->get('/admin/categories', function() { echo view('admin/categories'); });
        $this->router->get('/admin/classifications', function() { echo view('admin/classifications'); });
        $this->router->get('/admin/tags', function() { echo view('admin/tags'); });
        $this->router->get('/admin/media', function() { echo view('admin/media'); });
        $this->router->get('/admin/files', function() { echo view('admin/files'); });
        $this->router->get('/admin/users', function() { echo view('admin/users'); });
        $this->router->get('/admin/roles', function() { echo view('admin/roles'); });
        $this->router->get('/admin/permissions', function() { echo view('admin/permissions'); });
        $this->router->get('/admin/templates', function() { echo view('admin/templates'); });
        $this->router->get('/admin/api', function() { echo view('admin/api'); });
        $this->router->get('/admin/performance', function() { echo view('admin/performance'); });
        $this->router->get('/admin/testing', function() { echo view('admin/testing'); });
        $this->router->get('/admin/settings', function() { echo view('admin/settings'); });
        $this->router->get('/admin/security', function() { echo view('admin/security'); });
        $this->router->get('/admin/backup', function() { echo view('admin/backup'); });
        
        // 404 处理
        $this->router->notFound(function() {
            header("HTTP/1.0 404 Not Found");
            echo '404 Not Found';
        });
    }

    /**
     * 运行应用
     */
    public function run()
    {
        $this->router->dispatch();
    }
} 